<?php
/**
 * Created by PhpStorm.
 * User: zhao shou qiang
 * Date: 2018/1/4 0004
 * Time: 16:53
 */

namespace common\models;

use Yii;
use yii\base\Model;
use yii\db\Exception;
use yii\web\UploadedFile;

class UploadImgForm extends Model
{
    public $imageFiles;
    const PATH = 'uploads/investigation-file/';  //上传路径

    public function rules()
    {
        return [
            [['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpeg, jpg, gif', 'maxSize' => 30 * 1024 * 1024, 'maxFiles' => 20],
        ];
    }

    public function upload()
    {
        if ($this->validate()) {
            //生成目录
            $webroot = Yii::getAlias('@webroot');
            $path = str_replace('\\', '/', $webroot . '/' . self::PATH);
            if (!is_dir($path)) {
                mkdir($path);
            }

            $data = array();
            foreach ($this->imageFiles as $file) {
                $oldFileName = $file->baseName . '.' . $file->extension;
                $name = $this->guid() . '.' . $file->extension;
                $fileName = self::PATH . $name;
                if ($file->saveAs($fileName)) {
                    $size = $this->calcByte($file->size, 1);
                    $data[] = [
                        'size' => $size,
                        'olderFileName' => $oldFileName,
                        'fileName' => $name
                    ];
                }
            }
            return array('state' => true, 'msg' => '上传成功', 'data' => $data);
        } else {
            $message = '';
            $error = $this->getFirstErrors();
            if (!empty($error)) {
                foreach ($error as $value) {
                    $message .= $value;
                }
                $tmpStr = strip_tags($message);
                $tmpLen = mb_strlen($tmpStr);
                $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                return array('state' => false, 'msg' => $message);
            }
        }
    }

    /**
     * 生成uuid字符串
     * @return string
     */
    protected function guid()
    {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = //chr(123)// "{"
                substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12);
            //. chr(125);// "}"
            return $uuid;
        }
    }

    /**
     * 字节转换
     * @param $size 字节
     * @param int $digits 保留小数，默认两位
     * @return string 结果
     */
    protected function calcByte($size, $digits = 2)
    {
        $unit = array('', 'K', 'M', 'G', 'T', 'P');
        $base = 1024;
        $i = floor(log($size, $base));
        $n = count($unit);
        if ($i >= $n) {
            $i = $n - 1;
        }
        return round($size / pow($base, $i), $digits) . ' ' . $unit[$i] . 'B';
    }

}